package com.power.sifa.info.dao.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.info.model.Law_provision;
import com.power.sifa.util.CnwordUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.power.sifa.info.dao.Law_provisionDaoCustom;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;



/**
* 法律条文 持久层实现(hibernate)
*/
@Slf4j
@Repository
public class Law_provisionDaoImpl implements Law_provisionDaoCustom {

    private final JdbcTemplate jdbcTemplate;

    public Law_provisionDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public List<Law_provision> keywordfindAll(String docid, String keyword) {
        List<Law_provision> result = new ArrayList<>();
        String sql = "SELECT a.id, a.type, a.title, a.content, a.docid, ts_rank(a.convector,to_tsquery($1)) rk  FROM sfapprove.law_provision a WHERE  rk != 0 AND a.docid = $2 ORDER BY rk DESC";
        // 获得 keyword 的分词结果列表
        List<String> keywords = CnwordUtil.getSplitWords(keyword);
        // 将原始 keyword 添加到分词结果列表的开头
        //keywords.add(0, keyword);
        // 使用 String.join 将包含原 keyword 的列表转换成以 "&" 连接的字符串
        String Keywords = String.join("&", keywords);

        sql = sql.replace("$1", "'"+Keywords+"'");
        sql = sql.replace("$2", "'"+docid+"'");
        log.info(sql);


        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        List<Law_provision> list = jdbcTemplate.queryForList(sql,Law_provision.class);

//        List<Map> list = query.getResultList();
        if (CollectionUtil.isNotEmpty(list)) {
            for (Map<String, Object> objectMap : list) {
                String title = objectMap.get("title").toString();
                String content = objectMap.get("content").toString();

                objectMap.remove("title");
                objectMap.remove("content");

                objectMap.put("title", title);
                objectMap.put("content", content);

            }
            result = JSON.parseArray(JSON.toJSONString(list), Law_provision.class);
        }

        return result;
    }
}